package cn.gjxblog.controller;

import cn.gjxblog.entity.SocialUserInfo;
import cn.gjxblog.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.SecurityContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/1/15 16:54
 */
@RestController
public class UserController {

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @GetMapping("/user")
    public List<User> queryUser(){
        ArrayList<User> list = new ArrayList<>();
        User user1 = new User("1", "张飞", "123456");
        User user2 = new User("2", "关羽", "123456");
        User user3 = new User("3", "刘备", "123456");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        return list;
    }

    @GetMapping("/me")
    public Object getLoginUser(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @GetMapping("/social/user")
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        SocialUserInfo userInfo = new SocialUserInfo();
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        userInfo.setProviderId(connection.getKey().getProviderId());
        userInfo.setProviderUserId(connection.getKey().getProviderUserId());
        userInfo.setNickname(connection.getDisplayName());
        userInfo.setHeadimg(connection.getImageUrl());
        return userInfo;
    }
}
